package shin.SS.A1;

import java.util.Random;

import shin.SS.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;

public class activity extends Activity {
	
	private static boolean isOnClick = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        buttons[0] = (Button) findViewById(R.id.btn01);
        buttons[1] = (Button) findViewById(R.id.btn02);
        buttons[2] = (Button) findViewById(R.id.btn03);
        buttons[3] = (Button) findViewById(R.id.btn04);
        buttons[4] = (Button) findViewById(R.id.btn05);
        buttons[5] = (Button) findViewById(R.id.btn06);
        buttons[6] = (Button) findViewById(R.id.btn07);
        buttons[7] = (Button) findViewById(R.id.btn08);
        buttons[8] = (Button) findViewById(R.id.btnBlank);
     
        for(int i=0; i<8; i++)
        	buttons[i].setOnClickListener(on_Click);
        	
        	
        ((Button) findViewById(R.id.btnStart)).setOnClickListener(on_Start); 
    }
    
    private Button buttons[] = new Button[9];
    private void do_SwapButtons(Button A, Button B) {
    	int Left = A.getLeft();
    	int Top = A.getTop();
    	int Right = A.getRight();
    	int Bottom = A.getBottom();
    	
    	A.layout(B.getLeft(), B.getTop(), B.getRight(), B.getBottom());
    	B.layout(Left, Top, Right, Bottom);
    }
    
    private boolean IsVert(Button A, Button B)
    {
    	return ((A.getLeft() == B.getLeft()) &&
    			(Math.abs(A.getTop() - B.getTop()) <= 80));
    }
    
    private boolean IsHori(Button A, Button B)
    {
    	return ((A.getTop() == B.getTop()) &&
    			(Math.abs(A.getLeft() - B.getLeft()) <= 80));
    }
    
    private View.OnClickListener on_Click = new View.OnClickListener() {
		
		public void onClick(View v) {
			Button A = (Button) v;
			Button Blank = (Button) findViewById(R.id.btnBlank);

			if(IsVert(A, Blank) || IsHori(A, Blank))
			{
				do_SwapButtons(A, Blank);
				
				if(IsDonePuzzle())
					((TextView) findViewById(R.id.textView1)).setText("Congratulation!!");
			}
			
		}

		private boolean IsDonePuzzle() {
			int positionBtn = 0;
			
			for(int i=0; i<buttons.length; i++)
			{
				if(!(positionBtn == buttons[i].getLeft()))
					return false;
			}
			
			return true;
		}
	};
    
    private View.OnClickListener on_Start = new View.OnClickListener() {
		public void onClick(View v) {
			int x, y;
			for(y=0; y<3; y++){
				for(x=0; x<3; x++){
					buttons[y*3 + x].layout(x*80, y*80, x*80+80, y*80+80);
				}
			}
			
			Random randomBtn = new Random();
			
			for(int i=0; i<1000; i++)
				on_Click.onClick(buttons[randomBtn.nextInt(8)]);
		}
	};
}